package gwtadmin.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class UpdoServlet extends HttpServlet {
	
	private ServiceRegistry registry;
	
	public UpdoServlet() {
		super();
		registry = new ServiceRegistry("localhost:9001");
	}
	
	public UpdoServlet(ServiceRegistry serviceRegistry) {
		super();
		registry = serviceRegistry;
	}
	
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("download") != null) {
			try {
				String fileName = request.getParameter("download");
				String wsdl = registry.getWsdlFile(fileName);
				
				if (wsdl.equals("")) {
					response.sendError(HttpServletResponse.SC_BAD_REQUEST);
					return;
				}

				response.setContentType("application/octet-stream");
				response.addHeader("Content-Disposition",
						"attachment; filename=" + fileName);

				OutputStream os = response.getOutputStream();
				os.write(wsdl.getBytes());
				os.close();

			} catch (Exception ex) {

			}
		} else {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
//		Enumeration enAttr = request.getHeaderNames();
//		while (enAttr.hasMoreElements()) {
//			String hdrName = enAttr.nextElement().toString();
//			System.out.println(hdrName + ": " + request.getHeader(hdrName));
//		}

		PostData pd = extractData(request);

		registry.uploadWsdlFile(pd.fileName, new String(pd.data));
		
		response.setStatus(HttpServletResponse.SC_OK);
	}

	private String getBoundary(HttpServletRequest request) {
		String cType = request.getContentType();
		return cType.substring(cType.indexOf("boundary=") + 9);
	}
	
	public static byte[] readData(InputStream is, int length) throws IOException {
		byte[] data = new byte[length];
		int rd = is.read(data);
		while (rd < data.length && rd != -1) {
			rd = is.read(data, rd, data.length - rd);
		}
		is.close();

		return data;
	}
	
	private PostData extractData(HttpServletRequest request) throws IOException {
		
		byte[] data = readData(request.getInputStream(), request.getContentLength());
		
//		System.out.println(request.getContentLength());
//		System.out.println(rd);
//		System.out.println(				
//				new String(data)
//		);

		//////////////////////////////////////////////////////////////////////////
		
		int beginSliceIndex = 0;
		int endSliceIndex = data.length - getBoundary(request).length() - 9;
		
		final int CR = (byte)'\r';
		final int LF = (byte)'\n';
		
		for (int i = 0; i < data.length; i++) {
			if (data[i] == CR && data[i + 1] == LF && data[i + 2] == CR && data[i + 3] == LF) {
				beginSliceIndex = i + 4;
				break;
			}
		}
		
		//////////////////////////////////////////////////////////////////////////
		
		PostData postData = new PostData();
		
		postData.data = new byte[endSliceIndex - beginSliceIndex + 1];
		for (int i = beginSliceIndex; i <= endSliceIndex; i++) {
			postData.data[i - beginSliceIndex] = data[i];
		}
		
		//////////////////////////////////////////////////////////////////////////
		
		final String strFn = "; name=\"";
		
		String str = new String(data, 0, beginSliceIndex);
//		System.out.println(String.valueOf(beginSliceIndex));
		int ind1 = str.indexOf(strFn) + strFn.length();
		int ind2 = str.substring(ind1).indexOf('\"');
		
		postData.fileName = str.substring(ind1, ind1 + ind2);
		
		return postData;
	}
	
	private class PostData {
		public byte[] data = null;
		public String fileName = "";
	}
}
